/*
 * @Author: 胡海
 * @Date: 2020-02-21 18:23:26
 * @LastEditors: 胡海
 * @LastEditTime: 2020-03-07 21:17:44
 * @Description: 
 */
const {
    sequelize
} = require('../../core/db.js')


const {
    Sequelize,
    Model,
    Op
} = require('sequelize')

const {
    BuyOrder
} = require('./buyOrder')

// define
class ShoppingCart extends Model {
    // 业务表
    static async list (ctx, v) { //列表
        let obj = {
            count: v.get('body.count'),
            start: v.get('body.start'),
        }
        const total = await ShoppingCart.count()
        const list = await ShoppingCart.findAll({
            where: {
                uid: v.get('body.uid') || ctx.auth.uid
            },
            order: [
                ['id']
            ],
            limit: obj.count,
            offset: (obj.start - 1) * obj.count
        })
        const data = {
            list,
            total
        }
        return data
    }
    static async addGoods (ctx, v) { // 添加进购物车
        let data = {
            goodsIds: v.get('body.goodsIds'),
            uid: v.get('body.uid') || ctx.auth.uid
        }
        let arr = JSON.parse(data.goodsIds)
        for (let i = 0; i < arr.length; i++) {
            let good = await ShoppingCart.findOne({
                where: {
                    goodsId: arr[i]
                }
            })
            if (good) {
                return
            }
            let product = await Product.findOne({
                where: {
                    id: arr[i]
                }
            })
            let d = await ShoppingCart.create({
                ...product.dataValues,
                uid: data.uid,
                buyNum: 1,
                goodsId: arr[i]
            })
        }
    }
    static async commitBuyOrder (ctx, v) { // 订单
        let request = {
            list: v.get('body.list')
        }
        let orderSum = request.list.reduce((pre, cur) => {
            return cur.buyNum * cur.price + pre
        }, 0)
        BuyOrder.addBuyOrder(ctx, { orderSum })
    }
    static async editGoods (data) {
        let {
            id,
            ...all
        } = data
        const info = await ShoppingCart.update(all, {
            where: {
                id: data.id
            }
        })
    }
}

ShoppingCart.init({
    goodsName: Sequelize.STRING,
    coding: Sequelize.STRING,
    price: Sequelize.INTEGER,
    buyNum: Sequelize.INTEGER,
    stockNum: Sequelize.INTEGER,
    goodsId: Sequelize.INTEGER,
    uid: Sequelize.INTEGER,
}, {
    sequelize,
    tableName: 'shoppingCart',
    alter: true
})

module.exports = {
    ShoppingCart
}

// 数据迁移 SQL 更新 风险